<?php

namespace app\controller;

use app\general\utils\ConversionUtils;
use app\model\Column;
use app\model\WebUer;
use Carbon\Carbon;
use support\Db;
use support\Request;
use yzh52521\hash\Hash;


/**
 * 前台用户控制器
 */
class WebUserController extends BaseController
{

    /**
     * 输出验证码图像
     */
    public function login(Request $request)
    {
        $WebUser = WebUer::where('WebUser_name',$request->post('WebUsername'))->first();
        if(empty($WebUser)){
            return json($this->error('用户名活密码错误'));
        }
        if(Hash::check($request->post('password'), $WebUser->password)){
            return json($this->success('操作成功')) ;
        }
        return json($this->error('用户名活密码错误'));

    }

    /**
     * 检查验证码
     */
    public function check(Request $request)
    {
        // 获取post请求中的captcha字段
        $captcha = $request->post('captcha');
        // 对比session中的captcha值
        if (strtolower($captcha) !== $request->session()->get('captcha')) {
            return json(['code' => 400, 'msg' => '输入的验证码不正确']);
        }
        return json(['code' => 0, 'msg' => 'ok']);
    }

    public function index(Request $request)
    {

        $WebUsers = Db::table('web_user')
            ->when(is_numeric($request->input('status')) , function ($query) use ($request) {
                return $query->where('status', $request->input('status'));
            })->when($request->input('type'), function ($query) use ($request) {
                return $query->where('type', $request->input('type'));
            })
            ->paginate($request->get('pageSize'));
        $items = $WebUsers->items();
        foreach ($items as $key=>$val){
            $items[$key] = ConversionUtils::underscoreToHump($val) ;
            $items[$key]['createTime'] = Carbon::parse($items[$key]['createTime'])->toIso8601String();
        }

        return  json($this->success('操作成功',$items,$WebUsers->total()));
    }

    /**
     * 创建
     * @param Request $request
     * @return \support\Response
     */
    public function store(Request $request)
    {
        $column = new Column();
        $column->setRawAttributes(ConversionUtils::humpToUnderscore($request->all()));
        $column->version=0;
        $column->save();
        return  json($this->success('操作成功'));
    }

    /**
     * 更新
     * @param Request $request
     * @param $id
     * @return \support\Response
     */
    public function update(Request $request,$id)
    {
        $Column = Column::find($id);
        if(empty($Column)){
            return  json($this->success('操作失败'));
        }
        $data = $request->all();
        $data = ConversionUtils::humpToUnderscore($data);
        unset($data['create_time'],$data['updateTime']);
        $Column->setRawAttributes($data);
        $Column->save();
        return  json($this->success('操作成功'));
    }

    public function destroy(Request $request, $id)
    {
        Column::destroy($id) ;
        return  json($this->success('操作成功'));
    }

}
